package com.cinema.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cinema.api.constant.Roles;
import com.cinema.api.model.entity.Admin;
import com.cinema.api.mapper.AdminMapper;
import com.cinema.api.model.entity.Worker;
import com.cinema.api.model.enums.ResultCodeEnum;
import com.cinema.api.model.exception.BizException;
import com.cinema.api.model.vo.LoginVO;
import com.cinema.api.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinema.api.utils.BaseUtil;
import com.cinema.api.utils.JwtUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhh
 * @since 2021-12-31
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 进行用户信息校验 以及 生产Token并返回
     */
    @Override
    public String login(LoginVO loginVO) throws Exception {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.in("username",loginVO.getUsername())
                .eq("is_delete", 0);
        wrapper.in("password", loginVO.getPassword())
                .eq("is_delete", 0);
        Admin admin = adminMapper.selectOne(wrapper);
        if (BaseUtil.isEmpty(admin)) {
            throw new BizException(ResultCodeEnum.USERNAME_PASSWORD_NOT_FOUND);
        }
        // 是否记住我？（Token过期时间：一个星期&一天）
        long exp = loginVO.isRemember() ? JwtUtil.REMEMBER_EXPIRATION_TIME : JwtUtil.EXPIRATION_TIME;
        // 分配权限
        List<String> roles = new ArrayList<>();
        roles.add(Roles.ROLE_ADMIN);
        for (String role : Roles.ROLES) {
            roles.add(role);
        }
        System.out.println("role"+roles);
        return JwtUtil.createToken(loginVO.getUsername(),roles,exp);
    }

    /**
     *  获取管理员信息
     */
    @Override
    public Admin getAdmin(LoginVO loginVO) throws Exception {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.in("username", loginVO.getUsername())
                .eq("is_delete", 0);
        Admin admin = adminMapper.selectOne(wrapper);
        return admin;
    }
}
